//
//  SearchHistoryViewController.m
//  Tang
//
//  Created by 352324497@qq.com on 15/12/11.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "SearchHistoryViewController.h"
#import "HotSearchViewCell.h"
#import "CategorySegmentViewController.h"
@interface SearchHistoryViewController ()<UISearchBarDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong)UISearchBar *searchBar;
@property (nonatomic, strong)UIView *hotSearchView;
@property (nonatomic, strong)UICollectionView *hotSearchCollection;
@property (nonatomic, strong)NSString *text;
@end

@implementation SearchHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"搜索";
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self initView];
   
    
    if (self.titleArray.count != 0)
    {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        self.hotSearchCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0 , 60 * Kx6, KWidth, self.titleArray.count * (30 * Kx6 + 15 * Kx6) / 3) collectionViewLayout:layout];
        self.hotSearchView.height = self.titleArray.count * (30 * Kx6 + 15 * Kx6) / 3 + 60 * Kx6;
        self.hotSearchCollection.scrollEnabled = NO;
        self.hotSearchCollection.backgroundColor = [UIColor colorWithRed:240 / 255.0 green:240 / 255.0 blue:240 / 255.0 alpha:1];
        self.hotSearchCollection.showsHorizontalScrollIndicator = NO;
        self.hotSearchCollection.showsVerticalScrollIndicator = NO;
        self.hotSearchCollection.delegate = self;
        self.hotSearchCollection.dataSource = self;
        [self.hotSearchCollection registerClass:[HotSearchViewCell class] forCellWithReuseIdentifier:@"hotSearch"];
       // NSLog(@"00000000000");
        self.hotSearchView.height = self.titleArray.count * 30 * Kx6;
        [self.hotSearchView addSubview:_hotSearchCollection];
    }
}

#pragma 创建视图
-(void)initView
{
    self.hotSearchView = [[UIView alloc]initWithFrame:CGRectMake(0, 60 * Kx6, KWidth, 280 * Kx6)];
    self.hotSearchView.backgroundColor = [UIColor colorWithRed:240 / 255.0 green:240 / 255.0 blue:240 / 255.0 alpha:1];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 * Kx6, 20 * Kx6, KWidth - 40 * Kx6, 20 * Kx6)];
    titleLabel.text = @"热门搜索";
    titleLabel.textColor = [UIColor lightGrayColor];
    titleLabel.font = [UIFont systemFontOfSize:16 * Kx6];
    [self.hotSearchView addSubview:titleLabel];
    [self.view addSubview:_hotSearchView];
    
    // 自定义返回键
    // 返回的 button
    UIButton *leftBtn=[UIButton buttonWithType:(UIButtonTypeCustom)];
    leftBtn.frame = CGRectMake(0, 0, 25, 25);
    [leftBtn setImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];
    [leftBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftItem=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem=leftItem;
}
-(void)viewWillAppear:(BOOL)animated
{
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake((KWidth - 250 * Kx6) / 2, 10 * Kx6 , 250 * Kx6, 40 * Kx6)];
    self.searchBar.barStyle = UIBarButtonSystemItemDone;
    self.searchBar.keyboardType = UIKeyboardTypeDefault;
    // 取消键的颜色
    self.searchBar.tintColor = [UIColor orangeColor];
    self.searchBar.searchBarStyle = UIBarStyleBlackTranslucent;
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"搜索单品 / 清单";
    [self.view addSubview:_searchBar];
}

-(void)requestData
{
    [[NetworkState shareInstance]reachablityStatesWithDongHua:self];
    NSString *url = @"http://open3.bantangapp.com/base/search/hottags";
    NSString *string = @"app_installtime=1449053241.284786&app_versions=5.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&os_versions=9.1&screensize=640&track_device_info=iPhone6%2C2&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=9";
    NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
        [[[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            NSLog(@"请求失败");
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            [[NetworkState shareInstance] finshYYToVc:self];
            return ;
        }
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        self.titleArray = [NSMutableArray array];
            self.titleArray = Dic[@"data"];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.hotSearchCollection reloadData];
            [self.view setNeedsDisplay];
            [self.hotSearchView setNeedsDisplay];
            [self.hotSearchView setNeedsLayout];
            [[NetworkState shareInstance]finshYYToVc:self];
        });
    }]resume];
    
}


#pragma mark - collection
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.titleArray.count != 0)
    {
        return self.titleArray.count;
    }
    return 0;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10 * Kx6, 10 * Kx6, 10 * Kx6, 10 * Kx6);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(100 * Kx6, 30 * Kx6);
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotSearchViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hotSearch" forIndexPath:indexPath];
    cell.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cell.layer.borderWidth = 0.3;
    cell.layer.cornerRadius = 15 * Kx6;
    cell.backgroundColor = [UIColor whiteColor];
    if (self.titleArray.count != 0)
    {
        NSString *title = self.titleArray[indexPath.item];
        [cell setLabelWithTitle:title];
    }
    return cell;
}

#pragma mark - 返回
-(void)backAction:(UIButton *)button
{
    [self.searchBar removeFromSuperview];
    [self.navigationController popToRootViewControllerAnimated:NO];
}
#pragma mark - collection 点击
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = self.titleArray[indexPath.item];
    [self.searchBar removeFromSuperview];
    CategorySegmentViewController *categorySegmentVC = [[CategorySegmentViewController alloc]init];
    categorySegmentVC.text = title;
    [self.navigationController pushViewController:categorySegmentVC animated:NO];
    [self.searchBar removeFromSuperview];
}
#pragma mark - 是否开始编辑
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    
    [searchBar setShowsCancelButton:YES animated:YES];
    searchBar.showsCancelButton = YES;
    searchBar.frame = CGRectMake((KWidth - 300 * Kx6) / 2, 10 * Kx6 , 300 * Kx6, 30 * Kx6);
    UIButton *btn=[searchBar valueForKey:@"_cancelButton"];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    return YES;
    
}

#pragma mark - 点击取消键的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    searchBar.frame = CGRectMake((KWidth - 250 * Kx6) / 2, 10 * Kx6 , 250 * Kx6, 30 * Kx6);
    searchBar.text = nil;
    // 使键盘回收
    [searchBar resignFirstResponder];
}
#pragma mark - 获取输入的内容,
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;
{
    self.text = searchBar.text;
        [self.searchBar removeFromSuperview];
        CategorySegmentViewController *categorySegmentVC = [[CategorySegmentViewController alloc]init];
        categorySegmentVC.text = searchBar.text;
        [self.navigationController pushViewController:categorySegmentVC animated:NO];
        [self.searchBar removeFromSuperview];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
